﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Framework.Business;
using Framework.Entities.mysql;
using ServiceStack.Text;
using SignalPositionProcesser.DataAccess;
using SignalPositionProcesser.Entities;

namespace SignalPositionProcesser.Business
{
    public static class ImportChannelBusiness
    {
        public static void ImportChannelFromMysqlToNosql(ServiceContextBase<ImportChannelRequest, ImportChannelResponse> ctx)
        {
            var rawChannelList = RawdataDA.GetRawChannelList(ctx.Request.ImportChannelIdList);
            if (rawChannelList.IsNullOrEmpty())
            {
                ctx.Log("Not Found any channels.");
                return;
            }
            ctx.Log($"Get Channels from Mysql successfully, Count:[{rawChannelList.Count}]");

            var rawDeviceList = RawdataDA.GetRawDeviceList(rawChannelList.Select(r => r.ChannelUid).ToList());
            List<RawSignal> rawSignalList = new List<RawSignal>();
            if (!rawDeviceList.IsNullOrEmpty())
            {
                rawSignalList = RawdataDA.GetRawSignalList(rawDeviceList.Select(r => r.DeviceUid).ToList());
            }
            List<Channel> channels = new List<Channel>();

            foreach (var rawChannel in rawChannelList)
            {
                Channel channel = new Channel
                {
                    ChannelId = rawChannel.ChannelId,
                    ChannelName = rawChannel.ChannelName,
                };

                if (!rawDeviceList.IsNullOrEmpty())
                {
                    channel.DeviceList = rawDeviceList.Where(r => r.ChannelId == rawChannel.ChannelUid)
                        .Select(r =>
                        {
                            var device = new Device
                            {
                                DeviceId = r.DeviceId,
                                DeviceName = r.DeviceName,
                            };
                            if (!rawSignalList.IsNullOrEmpty())
                            {
                                device.SignalList = rawSignalList.Where(s => s.DeviceId == r.DeviceUid).Select(s =>
                                    new Signal
                                    {
                                        SignalId = s.SignalId,
                                        SignalName = s.SignalName,
                                        Unit = s.Unit
                                    }).ToList();
                            }
                            return device;
                        }).ToList();
                }

                channels.Add(channel);
            }

            ctx.Log(">>> Start to save Nosql.");

            ChannelDataDA channelDataDa = new ChannelDataDA();
            channelDataDa.SaveMany(channels);

            ctx.Log(">>> Save Nosql successfully.");

        }
    }
}
